package com.mantru.iotpot.dishes

import android.app.Application
import android.util.Log
import androidx.databinding.Observable
import androidx.databinding.ObservableField
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Bean.DishesShowBean
import com.mantru.iotpot.eventbus.EventMessage
import com.mantru.iotpot.eventbus.EventMessage.MSG_ID_OnHttpData_Image
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import kotlin.math.log

class DishesCreateImageViewModel(application: Application) : AndroidViewModel(application) {

    //突破搜索文本框内容
    val imageSearch = ObservableField<String>("")
    val vegetable_nameList = ObservableField<MutableList<String>>()
    val face_image_urlList = ObservableField<MutableList<String>>()
    //搜索内容，用于判断搜索的文字是否改变
    var searchName = "";
    //获取总共数据，当搜索内容发生改变时，要重新回到0
    var page_count = 0
    //统计当前数据页面，当滑动到recyclerview底部时，要计数加1，当搜索内容发生改变时，要重新回到1
    var pageStart = 1
    private val _dishesList = MutableLiveData<MutableList<DishesShowBean>>()
    val dishesList: LiveData<MutableList<DishesShowBean>> = _dishesList

    private val applicationClass: ApplicationClass = application as ApplicationClass

    // 初始化viewModel
    init {
        vegetable_nameList.set(mutableListOf())
        face_image_urlList.set(mutableListOf())
        // 注册EventBus
        EventBus.getDefault().register(this)
    }

    override fun onCleared() {
        super.onCleared()
        // 取消注册EventBus
        EventBus.getDefault().unregister(this)
    }

    //监听输入框的内容，当为空时重新获取数据
    fun startListeningToPictureSearch() {
        imageSearch.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                val searchQuery = imageSearch.get().toString()
                if (searchQuery.isEmpty()) {
                    //获取初始共享照片列表，此时内容为空
                    val map: MutableMap<String, Any> = HashMap()
                    getHttpValue("GetShareImage", map)
                }
            }
        })
    }

    // 更新菜品列表数据
    private fun updateDishesList() {
        //确保在主线程进行
        viewModelScope.launch(Dispatchers.Main) {
            val newList = mutableListOf<DishesShowBean>()
            if (vegetable_nameList.get()?.isNotEmpty() == true){
                for ( i in 0 until vegetable_nameList.get()!!.size){
                    newList.add(
                        DishesShowBean(
                            name = vegetable_nameList.get()?.get(i).toString(),
                            image = face_image_urlList.get()?.get(i).toString(),
                        )
                    )
                }
            }
            _dishesList.postValue(newList)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusMessage(event: EventMessage) {
        // 在这里处理EventBus事件
        when (event.id) {
            MSG_ID_OnHttpData_Image -> {//获取共享图片的http get请求
                val json = event.message
                if (!json.isNullOrEmpty()) {
                    try {
                        val jsonObject = JSONObject(json)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            //当page_count为0时，说明要么第一次进来，要吗搜索内容发生改变，要清除列表，重新计数
                            if ( page_count == 0 ){
                                vegetable_nameList.get()?.clear()
                                face_image_urlList.get()?.clear()
                            }
                            page_count = jsonObject.getInt("page_count")
                            val data = jsonObject.getJSONArray("data")
                            if ( data.length() > 0 ){
                                for (i in 0 until data.length()) {
                                    val jsonItem = data.getJSONObject(i)
                                    vegetable_nameList.get()?.add(jsonItem.getString("vegetable_name"))
                                    face_image_urlList.get()?.add(jsonItem.getString("face_image_url"))
                                }
                            }
                            updateDishesList()
                        } else {
                            Log.e("---GetShareImage", "API返回success=false")
                        }
                    } catch (e: Exception) {
                        Log.e("---GetShareImage:", e.toString())
                    }
                } else {
                    Log.e("---GetShareImage", "返回的JSON数据为空")
                }
            }
        }
    }

    //获取网络数据
    fun getHttpValue(api: String, map: Map<String, Any>){
        when ( api ){
            "GetShareImage" ->{//获取搜索菜谱
                //判断搜索内容是否发生改变，如果变了，那page_count和pageStart重新计算
                if ( searchName != imageSearch.get().toString() ){
                    page_count = 0
                    pageStart = 1
                    searchName = imageSearch.get().toString()
                }
                applicationClass.GetShareImage(pageStart, 15, imageSearch.get().toString())
            }
        }
    }
}